package com.mljqqh.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.pojo.Brand;
import com.mljqqh.mapper.BrandMapper;
import com.mljqqh.service.BrandService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/*

 */
@Service
public class BrandServiceImpl implements BrandService {
    @Autowired
    private BrandMapper brandMapper;

    @Override
    public PageResult<Brand> queryBrandsByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        // 1初始化example对象
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();
        //模糊查询
        if(StringUtils.isNotBlank(key)){
            criteria.andLike("name","%"+key+"%").orEqualTo("letter",key);
        }

        //添加分页
        PageHelper.startPage(page,rows);//(int pageNum, int pageSize) {
        //排序条件
        if (StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy+" "+(desc?"desc":"asc"));
        }
        List list = this.brandMapper.selectByExample(example);

        PageInfo<Brand> brandPageInfo = new PageInfo<>(list);

        return new PageResult<>(brandPageInfo.getTotal(),brandPageInfo.getList());
    }

    @Override
    @Transactional
    public void saveBrand(Brand brand, List<Long> cids) {
        //增加 brand表数据
        this.brandMapper.insertSelective(brand);

        //增加中间表数据INSERT INTO tb_category_brand (category_id,brand_id)VALUES(1,2)
        cids.forEach(cid->{
            this.brandMapper.insertCategoryAndBrand(cid,brand.getId());

        });


    }
}

